<script setup lang="ts">
import type {
  SkuPopupEvent,
  SkuPopupInstance,
  SkuPopupLocaldata,
} from "@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup";
import { postMemberCartAPI } from "@/api/cart";
import { avatarUrlImg } from "@/api/config/http";
import { getGoodsByIdAPI, getGoodsDatilAPI, postSale } from "@/api/goods";
import { onLoad, onPageScroll } from "@dcloudio/uni-app";
import { computed, onMounted, reactive, ref } from "vue";
import AddressPanel from "./components/AddressPanel.vue";
import ServicePanel from "./components/ServicePanel.vue";

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();

// 接收页面参数
const query = defineProps<{
  id: string;
}>();
//添加url地址合拼起来
const baseImageUrl = avatarUrlImg;
const getFullImagePath = (path: string) => {
  if (!path) return "";
  return path.startsWith("http") ? path : baseImageUrl + path;
};

// 获取商品详情信息
const goods = ref<any>();
const getGoodsByIdData = async () => {
  const res = await getGoodsByIdAPI();
  const mgs: any = await getGoodsDatilAPI(query.id);
  console.log("获取商品详情信息", mgs.data);
  // console.log("获取信息", res);
  // goods.value = res.result;
  goods.value = mgs.data;
};

// 轮播图变化时
const currentIndex = ref(0);
const onChange: UniHelper.SwiperOnChange = (ev) => {
  currentIndex.value = ev.detail.current;
};

// 点击图片时
const onTapImage = (url: string) => {
  // 大图预览
  uni.previewImage({
    current: url,
    urls: goods.value!.mainPictures,
  });
};

// uni-ui 弹出层组件 ref
const popup = ref<{
  open: (type?: UniHelper.UniPopupType) => void;
  close: () => void;
}>();

// 弹出层条件渲染
const popupName = ref<"address" | "service">();
const openPopup = (name: typeof popupName.value) => {
  // 修改弹出层名称
  popupName.value = name;
  popup.value?.open();
};
// 选中的地址
const selectedAddress = ref<string>("");

// 父组件接收地址选择
const onSelectAddress = (addr: any) => {
  selectedAddress.value = `${addr.fullLocation} ${addr.address}`;
  popup.value?.close();
};
// 是否显示SKU组件
const isShowSku = ref(false);
// 商品信息
const localdata = ref({} as SkuPopupLocaldata);
// 按钮模式
enum SkuMode {
  Both = 1,
  Cart = 2,
  Buy = 3,
}
const mode = ref<SkuMode>(SkuMode.Cart);
// 打开SKU弹窗修改按钮模式
const openSkuPopup = (val: SkuMode) => {
  // 显示SKU弹窗
  isShowSku.value = true;
  // 修改按钮模式
  mode.value = val;
};
// SKU组件实例
const skuPopupRef = ref<SkuPopupInstance>();
// 加入购物车事件
const onAddCart = async (ev: SkuPopupEvent) => {
  await postMemberCartAPI({ skuId: ev._id, count: ev.buy_num });
  uni.showToast({ title: "添加成功" });
  isShowSku.value = false;
};
// 立即购买
const onBuyNow = (ev: SkuPopupEvent) => {
  uni.navigateTo({
    url: `/pagesOrder/create/create?skuId=${ev._id}&count=${ev.buy_num}`,
  });
};
//
const hasMore = ref(true); // 是否还有更多数据
const isLoadingMore = ref(false); // 加载更多状态
const refresherTriggered = ref(false); // 下拉刷新状态
const current = ref(1);
const size = ref(10);
const goodsList = ref<any[]>([]);
const params = reactive({
  pageNum: 1,
  pageSize: 10,
});
const fetchOrderRecords = (isRefresh = false) => {
  if (isRefresh) {
    current.value = 1;
    hasMore.value = true;
  }
  if (!hasMore.value) return;
  isLoadingMore.value = true;
  setTimeout(async () => {
    const res = await postSale({
      pageNum: current.value,
      pageSize: params.pageSize,
      category: goods.value.category,
      // name: "",
    });
    const dataList = res.data.records;
    const newRecords = dataList.map((item) => ({
      ...item,
    }));
    if (isRefresh) {
      goodsList.value = newRecords;
    } else {
      goodsList.value.push(...newRecords);
    }
    hasMore.value = newRecords.length >= size.value;
    current.value++;
    isLoadingMore.value = false;
    refresherTriggered.value = false;
  }, 1000);
};
// 页面加载
onLoad(() => {
  getGoodsByIdData();
  fetchOrderRecords();
});
</script>

<template>
  <!-- SKU弹窗组件 -->
  <vk-data-goods-sku-popup v-model="isShowSku" :localdata="localdata" :mode="mode" add-cart-background-color="#FFA868"
    buy-now-background-color="#27BA9B" ref="skuPopupRef" :actived-style="{
      color: '#27BA9B',
      borderColor: '#27BA9B',
      backgroundColor: '#E9F8F5',
    }" @add-cart="onAddCart" @buy-now="onBuyNow" />
  <scroll-view enable-back-to-top scroll-y class="viewport">
    <!-- 基本信息 -->
    <view class="goods">
      <!-- 商品主图 -->
      <view class="preview">
        <swiper @change="onChange" circular>
          <swiper-item v-for="item in goods?.imageUrls" :key="item">
            <image class="image" @tap="onTapImage(item)" mode="aspectFill" :src="getFullImagePath(item)" />
          </swiper-item>
        </swiper>
        <view class="indicator">
          <text class="current">{{ currentIndex + 1 }}</text>
          <text class="split">/</text>
          <text class="total">{{ goods?.imageUrls.length }}</text>
        </view>
      </view>

      <!-- 商品简介 -->
      <view class="meta">
        <view class="price">
          <view class="name ellipsis">{{ goods?.name }} {{ goods?.description }}
          </view>
        </view>
        <view>
          <text class="symbol">¥</text>
          <text class="number">{{ goods?.price }}</text>
        </view>
      </view>

      <!-- 操作面板 -->
      <view class="action">
        <view @tap="openPopup('address')" class="item arrow">
          <text class="label">送至</text>
          <text class="text ellipsis">
            {{ selectedAddress || "请选择收货地址" }}
          </text>
        </view>
        <view @tap="openPopup('service')" class="item arrow">
          <text class="label">服务</text>
          <text class="text ellipsis"> 无忧退 快速退款 免费包邮 </text>
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="detail panel">
      <view class="title">
        <text>详情</text>
      </view>
      <view class="content">
        <view class="properties">
          <view class="item">
            <text class="label">适用季节</text>
            <text class="value">{{ goods.season }}</text>
          </view>
        </view>
        <view class="content-title">
          <text class="title-style">{{ goods.introduce }}</text>
        </view>
        <!-- 图片详情 -->
        <view class="imags">
          <image class="image" v-for="item in goods?.imageUrls" :key="item" mode="widthFix"
            :src="getFullImagePath(item)"></image>
        </view>
      </view>
    </view>

    <!-- 同类推荐 -->
    <view class="similar panel">
      <view class="title">
        <text>同类推荐</text>
      </view>
      <view class="goods-list">
        <navigator class="goods-card" v-for="(item, index) in goodsList" :key="item.id"
          :url="`/pages/goods/goods?id=${item.id}`">
          <image :src="getFullImagePath(item.imageUrls[0])" mode="aspectFill" class="goods-image" />
          <view class="goods-info">
            <view class="goods-top">
              <text class="goods-name">{{ item.name }} {{ item.description }}</text>
            </view>
            <view class="content-boxs">
              <text class="goods-price">¥{{ item.price }}</text>
            </view>
            <view class="goods-bottom">
              <view class="goods-img">
                <image :src="getFullImagePath(item.userAvatar)" mode="scaleToFill" class="images" />
              </view>
              <view class="goods-footer">
                <text class="goods-status" :class="item.statusSale === '1' ? 'onsale' : 'offsale'">
                  {{ item.statusSale === "1" ? "已挂售" : "未挂售" }}
                </text>
                <text class="goods-season">{{ item.season }}</text>
              </view>
            </view>
          </view>
        </navigator>
      </view>

      <view class="bortoom"></view>
    </view>
  </scroll-view>

  <!-- 用户操作 -->
  <view v-if="goods" class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <view class="icons">
      <button class="icons-button"><text class="icon-heart"></text>收藏</button>
      <!-- #ifdef MP-WEIXIN -->
      <button class="icons-button" open-type="contact">
        <text class="icon-handset"></text>客服
      </button>
      <!-- #endif -->
      <navigator class="icons-button" url="/pages/cart/cart2" open-type="navigate">
        <text class="icon-cart"></text>购物车
      </navigator>
    </view>
    <view class="buttons">
      <view @tap="openSkuPopup(SkuMode.Cart)" class="addcart">
        加入购物车
      </view>
      <view @tap="openSkuPopup(SkuMode.Buy)" class="payment"> 立即购买 </view>
    </view>
  </view>

  <!-- uni-ui 弹出层 -->
  <uni-popup ref="popup" type="bottom" background-color="#fff">
    <AddressPanel v-if="popupName === 'address'" @close="popup?.close()" @select="onSelectAddress" />
    <ServicePanel v-if="popupName === 'service'" @close="popup?.close()" />
  </uni-popup>
</template>

<style lang="scss">
.viewport {
  background-color: #f4f4f4;
}

.panel {
  margin-top: 20rpx;
  background-color: #fff;

  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 90rpx;
    line-height: 1;
    padding: 30rpx 60rpx 30rpx 6rpx;
    position: relative;

    text {
      padding-left: 10rpx;
      font-size: 28rpx;
      color: #333;
      font-weight: 600;
      border-left: 4rpx solid #27ba9b;
    }

    navigator {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.arrow {
  &::after {
    position: absolute;
    top: 50%;
    right: 30rpx;
    content: "\e6c2";
    color: #ccc;
    font-family: "erabbit" !important;
    font-size: 32rpx;
    transform: translateY(-50%);
  }
}

/* 商品信息 */
.goods {
  background-color: #fff;

  .preview {
    height: 750rpx;
    position: relative;

    swiper {
      width: 100%;
      height: 100%;
      display: block;
    }

    swiper-item {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .image {
      width: 100%;
      height: 100%;
      object-fit: cover;
      display: block;
    }

    .indicator {
      height: 40rpx;
      padding: 0 24rpx;
      line-height: 40rpx;
      border-radius: 30rpx;
      color: #fff;
      font-family: Arial, Helvetica, sans-serif;
      background-color: rgba(0, 0, 0, 0.3);
      position: absolute;
      bottom: 30rpx;
      right: 30rpx;

      .current {
        font-size: 26rpx;
      }

      .split {
        font-size: 24rpx;
        margin: 0 1rpx 0 2rpx;
      }

      .total {
        font-size: 24rpx;
      }
    }
  }

  .meta {
    display: flex;
    position: relative;
    flex-direction: column;
    border-bottom: 1rpx solid #eaeaea;

    .price {
      height: 130rpx;
      display: flex;
      align-items: center;
      font-size: 34rpx;
      box-sizing: border-box;
      background-color: rgb(216, 234, 226);

      .name {
        margin: 20rpx;
        font-size: 36rpx;
        color: #333;
      }
    }

    .symbol {
      color: #ffa868;
    }

    .number {
      color: #cf4444;
      font-size: 48rpx;
    }
  }

  .action {
    padding-left: 20rpx;

    .item {
      height: 90rpx;
      padding-right: 60rpx;
      border-bottom: 1rpx solid #eaeaea;
      font-size: 26rpx;
      color: #333;
      position: relative;
      display: flex;
      align-items: center;

      &:last-child {
        border-bottom: 0 none;
      }
    }

    .label {
      width: 60rpx;
      color: #898b94;
      margin: 0 16rpx 0 10rpx;
    }

    .text {
      flex: 1;
      -webkit-line-clamp: 1;
    }
  }
}

/* 商品详情 */
.detail {
  padding-left: 20rpx;

  .content {
    margin-left: -20rpx;

    .imags {
      padding: 20rpx 40rpx 40rpx;

      .image {
        width: 100%;
      }
    }
  }

  .properties {
    padding: 0 20rpx;
    margin-bottom: 30rpx;

    .item {
      display: flex;
      line-height: 2;
      padding: 10rpx;
      font-size: 26rpx;
      color: #333;
      border-bottom: 1rpx dashed #ccc;
    }

    .label {
      width: 200rpx;
    }

    .value {
      flex: 1;
    }
  }
}

/* 同类推荐 */
.similar {
  .content {
    padding: 0 10rpx 10rpx;
    background-color: #f4f4f4;
    display: flex;
    flex-wrap: wrap;

    .goods {
      width: 320rpx;
      padding: 24rpx 20rpx 20rpx;
      margin: 20rpx 5rpx;
      border-radius: 10rpx;
      background-color: #fff;
    }

    .image {
      width: 300rpx;
      height: 260rpx;
    }

    .name {
      height: 80rpx;
      margin: 10rpx 0;
      font-size: 26rpx;
      color: #262626;
    }

    .price {
      line-height: 1;
      font-size: 20rpx;
      color: #cf4444;
    }

    .number {
      font-size: 26rpx;
      margin-left: 2rpx;
    }
  }

  navigator {
    &:nth-child(even) {
      margin-right: 0;
    }
  }
}

/* 底部工具栏 */
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc((var(--window-bottom)));
  z-index: 1;
  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx;
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;

  .buttons {
    display: flex;

    &>view {
      width: 220rpx;
      text-align: center;
      line-height: 72rpx;
      font-size: 26rpx;
      color: #fff;
      border-radius: 72rpx;
    }

    .addcart {
      background-color: #ffa868;
    }

    .payment {
      //   background-color: #27ba9b;
      background-color: rgb(216, 234, 226);
      margin-left: 20rpx;
    }
  }

  .icons {
    padding-right: 20rpx;
    display: flex;
    align-items: center;
    flex: 1;

    // 兼容 H5 端和 App 端的导航链接样式
    .navigator-wrap,
    .icons-button {
      flex: 1;
      text-align: center;
      line-height: 1.4;
      padding: 0;
      margin: 0;
      border-radius: 0;
      font-size: 20rpx;
      color: #333;
      background-color: #fff;

      &::after {
        border: none;
      }
    }

    text {
      display: block;
      font-size: 34rpx;
    }
  }
}

.bortoom {
  height: 180rpx;
}

.content-title {
  height: 100%;
  display: flex;
  padding: 20rpx;
  justify-content: center;
  align-items: center;

  .title-style {
    color: #666;
  }
}
</style>
<style lang="scss">
.goods-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin: 0 20rpx;

  .goods-card {
    width: 48%;
    background: #fff;
    border-radius: 10rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
    margin-bottom: 12rpx;

    .goods-image {
      width: 100%;
      height: 250rpx;
      object-fit: cover;
    }

    .goods-info {
      padding: 10rpx;

      .goods-top {
        display: flex;
        height: 80rpx;

        .goods-name {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
          display: block;
          margin-bottom: 4rpx;
        }
      }

      .content-boxs {
        .goods-price {
          font-size: 28rpx;
          color: #ff4d4f;
          margin-bottom: 6rpx;
        }
      }

      .goods-bottom {
        display: flex;
        height: 100rpx;

        .goods-img {
          flex: 1;
          display: flex;
          align-items: center;

          .images {
            width: 80rpx;
            border-radius: 50%;
            height: 80rpx;
          }
        }

        .goods-footer {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          align-items: center;

          .goods-status {
            font-size: 24rpx;
            padding: 2rpx 6rpx;
            border-radius: 4rpx;

            &.onsale {
              color: #52c41a;
              border: 1rpx solid #52c41a;
            }

            &.offsale {
              color: #999;
              border: 1rpx solid #ccc;
            }
          }

          .goods-season {
            font-size: 22rpx;
            color: #666;
          }
        }
      }
    }
  }
}
</style>
